package com.fiap.activities;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.fiap.dao.UserOperations;
import com.fiap.functions.UserFunctions;
import com.fiap.model.User;

public class SocialEngineViewer extends Activity implements OnTouchListener,
		Handler.Callback {

	// Javascript interface
	NativeJavascriptInterface nativeInterface;

	// Constant attributes
	// private static final String serverInitialAddress =
	// "http://runnersteam.no-ip.biz/socialengine45/members/home";
	private static final String serverInitialAddress = "http://10.0.2.2/socialengine45/members/home";

	// Class variables
	private static final int CLICK_ON_WEBVIEW = 1;
	private static final int CLICK_ON_URL = 2;
	private final Handler handler = new Handler(this);
	private WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.socialengine_webview);

		nativeInterface = new NativeJavascriptInterface(getApplicationContext());

		webView = (WebView) findViewById(R.id.web_view);
		webView.setOnTouchListener(this);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl(serverInitialAddress);

		this.webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.contains("activities")) {
					webView.addJavascriptInterface(nativeInterface, "accessor");
					webView.loadUrl(serverInitialAddress);

					Intent activitiesMenu = new Intent(getApplicationContext(),
							GPSActivity.class);
					activitiesMenu.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(activitiesMenu);
				} else {
					view.loadUrl(url);
				}

				return true;
			}
		});
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (v.getId() == R.id.web_view
				&& event.getAction() == MotionEvent.ACTION_DOWN) {
			handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
		}
		return false;
	}

	@Override
	public boolean handleMessage(Message msg) {
		if (msg.what == CLICK_ON_URL) {
			handler.removeMessages(CLICK_ON_WEBVIEW);
			return true;
		}
		if (msg.what == CLICK_ON_WEBVIEW) {
			// Toast.makeText(this, "WebView clicked",
			// Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}

	public class NativeJavascriptInterface {
		Context context;

		/** Instantiate the interface and set the context */
		NativeJavascriptInterface(Context c) {
			context = c;
		}

		/**
		 * @param refers
		 *            to the en4.user.viewer.id variable from javascript For
		 *            more information, look for the "teste" widget in the
		 *            socialengine website.
		 */
		@SuppressWarnings("unused")
		public void setValue(String id) {
			if (Integer.parseInt(id) != 0) {
				try {
					int userId = Integer.parseInt(id);
					User user;
					UserFunctions userFunction = new UserFunctions();
					UserOperations userOperations = new UserOperations(
							getApplicationContext());
					JSONObject json = userFunction.loginUser(userId);
					JSONObject jsonUser = json.getJSONObject("user");
					
					String userName = jsonUser.getString("username");
					String userEmail = jsonUser.getString("email");

					// Check if the user is already in the SQLite
					user = userOperations.getUser(userId);
					if (user == null) {
						// If the user is not in the SQLite, insert his/her info.
						userOperations.insertUser(userId,
												  userName,
												  userEmail);
					} 
					SharedPreferences preferences = PreferenceManager
							.getDefaultSharedPreferences(getApplicationContext());
					Editor editor = preferences.edit();
					editor.putInt("userId", userId);
					editor.putString("userName", userName);
					editor.putString("userEmail", userEmail);
					editor.commit();
				} catch (JSONException e) {
					Log.d("SocialEngineViewer_NativeJavascriptInterface_setValue",
							"JSON Exception");
				}
			}
		}
	}

}
